/**
 * 统一管理渲染各个组件的方法
 */
layui.define(['form', 'zlConfig', 'element', 'zlContext', 'laydate', 'table', 'upload'], function (exports) {
    "use strict";
    var $ = layui.$
        , zlContext = layui.zlContext
        , form = layui.form
        , element = layui.element
        , laydate = layui.laydate
        , upload = layui.upload
        , table = layui.table
        , zlConfig = layui.zlConfig
        , statusName = zlConfig.global.result.statusName
        , msgName = zlConfig.global.result.msgName
        , dataName = zlConfig.global.result.dataName
        // , ERROR = zlConfig.global.result.errorState
        , OK = zlConfig.global.result.okState
        , zlComponentRender = {
            /**渲染tabs */
            tabs: function (options, $parent, tabs) {
                var tabHtml = [], pages = {};
                if (tabs && tabs.length > 0) {
                    tabHtml.push('<div class="layui-tab layui-tab-card layui-col-md12">');
                    tabHtml.push('  <ul class="layui-tab-title">');
                    $.each(tabs, function (i, tab) {
                        tabHtml.push(' <li ' + (i == 0 ? 'class="layui-this"' : '') + '>' + tab.title + '</li>');
                    });
                    tabHtml.push(' </ul>');
                    tabHtml.push('<div class="layui-tab-content">');
                    $.each(tabs, function (i, tab) {
                        var tabPageId = "p" + zlContext.generateId();
                        tabHtml.push('<div id="' + tabPageId + '" class="layui-tab-item' + (i == 0 ? ' layui-show"' : '"') + '>');
                        tabHtml.push('</div>')
                        pages[tabPageId] = tab;
                    });
                    tabHtml.push('</div>');
                }
                $parent.append(tabHtml.join(''));
                for (var key in pages) {
                    var pageElem = $('#' + key);
                    if (pages[key].grids && pages[key].grids.length > 0) {
                        zlComponentRender.grids(options, pageElem, pages[key].grids);
                    }
                    if (pages[key].forms && pages[key].forms.length > 0) {
                        tabHtml.push(options, pageElem, pages[key].forms);
                    }
                }
                element.render();
            },
            /**渲染forms */
            forms: function (options, $parent, frmsOptions) {
                var fhtml = [],
                    ret = [];
                //渲染脚本
                zlComponentRender.scripts(options.scripts);
                //渲染校验
                zlComponentRender.verifys(options.verifys);
                $.each(frmsOptions, function (i, frmOptions) {
                    var formId = zlContext.generateId();
                    // hidframeId = zlContext.generateId()
                    if (frmOptions.fields && frmOptions.fields.length > 0) {
                        fhtml.push('<form class="layui-form layui-form-pane" id="' + formId + '" lay-filter="' + formId + '"></form>');
                        var frmElem = $(fhtml.join(''));
                        $parent.append(frmElem);
                        //渲染按钮
                        var btnIds = zlComponentRender.buttons(options, frmElem, frmOptions.buttons);
                        //渲染字段
                        zlComponentRender.fields(options, frmElem, frmOptions.fields);
                        //渲染form
                        form.render(null, formId);
                        //添加表单验证规则
                        if (!zlContext.isEmpty(zlConfig.global.verify)) {
                            form.verify(zlConfig.global.verify);
                        }
                        $.each(options.verifys, function (i, verify) {
                            for (var key in verify) {
                                form.verify(eval(key));
                            }
                        });
                        //监听提交
                        $.each(btnIds, function (i, btnId) {
                            // var type = $('#' + btnId).attr('type');
                            form.on('submit(' + btnId + ')', function (result) {
                                var url = $(this).attr("url"),
                                    title = this.innerText;
                                    // param = JSON.stringify(result.field)
                                if (zlContext.isEmpty(url)) {
                                    zlContext.errorMsg("url 为空无法提交");
                                    return false;
                                }
                                parent.layer.close(parent.layer.getFrameIndex(window.name));
                                zlContext.post(url, result.field, function (result) {
                                    if (result[statusName] == OK) {
                                        zlContext.successMsg(title + " 成功");
                                        layui.event("WM_USERDEF", zlConfig.global.WM_USERDEF.REFRESH_TREE_DATA_DATA, result[dataName]);
                                    }
                                    else {
                                        zlContext.errorMsg(result[msgName]);
                                    }
                                });
                                return false;
                            });
                        });
                        //监听刷新的事件
                        layui.event("WM_USERDEF", zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null, function (param) {
                            zlComponentRender.loadFormData(options, frmElem, frmOptions, param);
                        });
                        ret.push(frmElem);
                    }
                });
                return ret;
            },
            /** 渲染form数据　使用远程数据 */
            loadFormData: function (options, frmElem, frmOptions, param) {
                zlContext.get(frmOptions.url, { id: param }, function (result) {
                    if (result[statusName] == OK) {
                        zlContext.autoFill(frmElem, result[dataName], frmOptions);
                    }
                    else {
                        zlContext.errorMsg(result[msgName]);
                    }
                });
            },
            /**重新加载grid数据 */
            loadGridData: function (options, tableId, gridOptions, param) {
                table.reload(tableId, {
                    url: gridOptions.url,
                    where: param
                });
            },
            /** 渲染form数据　使用本地数据 */
            loadFormLocateData: function (options, frmElem, frmOptions, data) {
                zlContext.autoFill(frmElem, data, frmOptions);
            },
            /**渲染grids */
            grids: function (options, $parent, gridsOptions) {
                var btnhtml = []
                    , gridHtml = []
                    , btnColHtml = [];
                $.each(gridsOptions, function (i, gridOptions) {
                    btnhtml = [];
                    gridHtml = [];
                    btnColHtml = [];
                    if (gridOptions && gridOptions.columns && gridOptions.columns.length > 0) {
                        /**增加table的按钮节点 新增修改删除导出打印保存等.... */
                        if (gridOptions.buttons && gridOptions.buttons.length > 0) {
                            btnhtml.push('<div class="layui-col-md12 layui-btn-container gridtoolbar">');
                            $.each(gridOptions.buttons, function (index, button) {
                                btnhtml.push('<button class="layui-btn layui-btn-sm" data-type="' + button.id + '" url="' + button.url + '">');
                                btnhtml.push('    <i class="layui-icon">' + button.icon + '</i>' + button.text);
                                btnhtml.push('</button>');
                            });
                            btnhtml.push('</div>');
                        }
                        /**增加table节点 */
                        var tableId = "table_" + zlContext.generateId();
                        gridHtml.push('<div class="layui-col-md12">');
                        gridHtml.push('<table id="' + tableId + '" class="layui-table"  lay-filter="' + tableId + '"></table>');
                        gridHtml.push('</div');
                        /**遍历列 并生成按钮操作按钮 */
                        $.each(gridOptions.columns, function (index, column) {
                            if (column.buttons && column.buttons.length > 0) {
                                var toobbarId = 'btn_' + tableId;
                                btnColHtml.push('<script type="text/html" id="' + toobbarId + '">');
                                $.each(column.buttons, function (i, btn) {
                                    btnColHtml.push('<a class="' + btn.clz + '" lay-event="' + btn.event + '">' + btn.text + '</a>');
                                });
                                btnColHtml.push('</script>');
                                $parent.append(btnColHtml.join(''));
                                column.toolbar = '#' + toobbarId;
                            }
                        });
                        $parent.append(btnhtml.join('') + gridHtml.join(''));
                        /**渲染 columns */
                        table.render({
                            elem: '#' + tableId
                            //, url: gridOptions.url
                            , height: gridOptions.height
                            , id: tableId
                            , cellMinWidth: 80
                            , page: true //开启分页
                            , cols: [gridOptions.columns]
                            , response: zlConfig.global.gridResponse
                        });
                        /**事件处理 */
                        /**grid内的按钮事件 */
                        table.on('tool(' + tableId + ')', function (obj) {
                            var data = obj.data;
                            if (obj.event === 'detail') {
                                layer.msg('ID：' + data.id + ' 的查看操作');
                            } else if (obj.event === 'del') {
                                layer.confirm('是否删除行?', function (index) {
                                    obj.del();
                                    layer.close(index);
                                });

                            } else if (obj.event === 'edit') {
                                //layer.alert('编辑行：<br>' + JSON.stringify(data))
                                layui.use('zlGridEditForm', function () {
                                    var $ = layui.$
                                        , zlGridEditForm = layui.zlGridEditForm;
                                    zlGridEditForm.show(data, options, gridOptions, null, 'edit');
                                });
                            }
                        });
                        /**grid上部分的按钮事件 */
                        var toolbarEvent = {
                            add: function (btn) {
                                var checkStatus = table.checkStatus(tableId)
                                    , data = checkStatus.data;
                                //layer.alert('新增' + JSON.stringify(data));
                                layui.use('zlGridEditForm', function () {
                                    var $ = layui.$
                                        , zlGridEditForm = layui.zlGridEditForm;
                                    zlGridEditForm.show(null, options, gridOptions, null, 'new');
                                });
                            }
                            , del: function () {
                                var checkStatus = table.checkStatus(tableId)
                                    , data = checkStatus.data;
                                layer.alert('删除' + JSON.stringify(data));
                            }
                            , print: function () {
                                var checkStatus = table.checkStatus(tableId)
                                    , data = checkStatus.data;
                                layer.alert('打印' + JSON.stringify(data));
                            }
                            , exp: function () {
                                var checkStatus = table.checkStatus(tableId)
                                    , data = checkStatus.data;
                                layer.alert('导出' + JSON.stringify(data));
                            }
                            , save: function () {
                                var checkStatus = table.checkStatus(tableId)
                                    , data = checkStatus.data;
                                layer.alert('保存' + JSON.stringify(data));
                            }
                        };
                        $parent.find('.gridtoolbar .layui-btn').on('click', function () {
                            var type = $(this).data('type');
                            toolbarEvent[type] ? toolbarEvent[type].call(this) : '';
                        });
                        //监听刷新的事件
                        layui.event("WM_USERDEF", zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null, function (param) {
                            var loadopt = {
                                page: { curr: 1 }
                            };
                            var gops = {};
                            $.extend(gops, gridOptions);
                            gops.url = zlContext.format(gops.url, param);
                            zlComponentRender.loadGridData(options, tableId, gops, loadopt);
                        });
                    }
                });
            },
            /**渲染树 */
            tree: function (options, $parent, treeOptions) {
                // console.log(options);
                // console.log(treeOptions);
                var h = []
                    // , ret = {}
                    , treeId = zlContext.generateId()
                    , btnClass = 'btngroup-' + treeId;
                if (treeOptions.readOnly != undefined && treeOptions.readOnly != 1 && treeOptions.buttons && treeOptions.buttons.length > 0) {
                    h.push('<div class="layui-btn-group">')
                    $.each(treeOptions.buttons, function (i, btn) {
                        var url = btn.url ? '" url="' + btn.url + '"' : ''
                            , dataType = 'data-type="' + btn.id + '"';
                        h.push('<button class="layui-btn layui-btn-primary layui-btn-sm ' + btnClass + '"' + dataType + url + '>' + btn.text + '</button>');
                    })
                    h.push('</div>')
                }
                if (treeOptions.search == 1) {
                    var searchId = zlContext.generateId();
                    h.push('<input type="text" id="' + searchId + '" placeholder="请输入查找的节点值" autocomplete="off" class="layui-input">');
                }
                h.push('<div class="layui-col-md12">');
                h.push('    <ul id="' + treeId + '" class="ztree" url="/fsbus/S1003"></ul>');
                h.push('</div>');
                $parent.append(h.join(''));
                //创建zTree组件
                var setting = {
                    view: {
                        showLine: true
                    },
                    async: {
                        enable: true,
                        url: treeOptions.url,
                        type: "get",
                        dataFilter: function ajaxDataFilter(treeId, parentNode, responseData) {
                            if (responseData[statusName] == OK) {
                                return responseData[dataName];
                            }
                            else {
                                zlContext.errorMsg(data[msgName]);
                            }
                            return responseData;
                        }
                    },
                    data: {
                        key: {
                            name: treeOptions.nameKey
                        }
                        , simpleData: {
                            enable: true
                            , idKey: treeOptions.idKey
                            , pIdKey: treeOptions.pIdKey
                            , rootPid: treeOptions.rootPid
                        }
                    },
                    callback: {
                        onClick: function (event, treeId, treeNode) {
                            //触发注册刷新的事件
                            layui.event("WM_USERDEF", zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, treeNode[treeOptions.idKey]);
                        }
                        // ,callback: {
                        //     beforeDrag: zTreeBeforeDrag
                        // }
                    }
                };
                $.fn.zTree.init($("#" + treeId), setting, null);
                //监听树节点刷新的事件
                layui.event("WM_USERDEF", zlConfig.global.WM_USERDEF.REFRESH_TREE_DATA_DATA, null, function (node) {
                    //treeObj.updateNode(node);
                    alert('223');
                    // console.log('2212');
                });
                //注册点击tree的按钮触发的事件 新增修改,删除
                var treeObj = $.fn.zTree.getZTreeObj(treeId),
                    treeBtnAction = {
                    checkSelected: function () {
                        var nodes = treeObj.getSelectedNodes();
                        if (nodes.length == 0)
                            zlContext.errorMsg("需选择节点");
                        return nodes.length > 0;
                    },
                    /**新增别的类型 */
                    treeNewDic: function () {
                        treeBtnAction.treeNew("dict");
                    },
                    /**新增 */
                    treeNew: function (type) {
                        if (treeBtnAction.checkSelected()) {
                            var nd = treeObj.getSelectedNodes()[0];
                            layui.use('zlTreeEditForm', function () {
                                var $ = layui.$
                                    , zlTreeEditForm = layui.zlTreeEditForm
                                    //新增的默认值
                                    , defValues = {
                                        SYS_PARENTID: nd[treeObj.setting.data.simpleData.idKey]
                                        , SYS_PARENTS: nd.SYS_PARENTS
                                        , SYS_ISLEAF: nd.SYS_ISLEAF
                                        , tbId: treeOptions.editForms[0].tbId
                                    };
                                zlTreeEditForm.show(nd, options, defValues, 'new');
                            });
                        }
                    },
                    /**编辑 */
                    treeEdit: function () {
                        if (treeBtnAction.checkSelected()) {
                            var nd = treeObj.getSelectedNodes()[0];
                            layui.use('zlTreeEditForm', function () {
                                var $ = layui.$
                                    , zlTreeEditForm = layui.zlTreeEditForm
                                    //编辑的默认值
                                    , defValues = {
                                        SYS_PARENTID: nd.SYS_PARENTID
                                        , SYS_PARENTS: nd.SYS_PARENTS
                                        , SYS_ISLEAF: nd.SYS_ISLEAF
                                        , tbId: treeOptions.editForms[0].tbId
                                    };
                                zlTreeEditForm.show(nd, options, defValues, 'edit');
                            });
                        }
                    },
                    /**删除 */
                    treeDelete: function () {
                        var nodes = treeObj.getSelectedNodes(),
                            that = this,
                            param = {};
                        zlContext.confirm('询问', '是否要删除选择的节点', function (index) {
                            for (var i = 0, l = nodes.length; i < l; i++) {
                                var url = $(that).attr('url'),
                                    nd = nodes[i];
                                param[treeObj.setting.data.simpleData.idKey] = nd[treeObj.setting.data.simpleData.idKey];
                                param['tbId'] = treeOptions.editForms[0].tbId;
                                //提交删除
                                zlContext.post(url, param, function (result) {
                                    if (result[statusName] == OK) {
                                        //刷新页面
                                        treeObj.removeNode(nd);
                                    }
                                    else {
                                        zlContext.errorMsg(result[msgName]);
                                    }
                                });
                            }
                            layer.close(index);
                        });
                    },
                    /**修改位置 */
                    treeChangePost: function () {
                        alert('还没实现哦');
                    },
                    /**刷新 */
                    treeRefresh: function () {
                        $.fn.zTree.init($("#" + treeId), setting, null);
                    }
                };
                if (treeOptions.buttons.length > 0)
                    $('.' + btnClass).on('click', function () {
                        var othis = $(this), type = othis.data('type');
                        treeBtnAction[type] ? treeBtnAction[type].call(this, othis) : '';
                    });

                return { tree: $(treeId) };
            },
            fields: function (options, $parent, fields) {
                $.each(fields, function (i, field) {
                    if (field.type && zlComponentRender[field.type]) {
                        var $item = $('<div class="layui-form-item"></div>')
                        $parent.append($item);
                        zlComponentRender[field.type](options, $item, field);
                    }
                });
            },
            /**渲染左右布局 */
            layoutLeftRigth: function (options, $parent, tree) {
                var h = [],
                    leftId = zlContext.generateId(),
                    rightId = zlContext.generateId();
                h.push('<div  class="layui-row layui-col-space10">');
                h.push('    <div id ="' + leftId + '" class="layui-col-md3"></div>');
                h.push('    <div id ="' + rightId + '" class="layui-col-md9"></div>');
                h.push('</div>');
                $parent.append(h.join(''));
                return { left: $('#' + leftId), right: $('#' + rightId) };
            },
            /**渲染上下布局 */
            layoutUpDown: function (options, $parent, tree) {
                var h = [],
                    upId = zlContext.generateId(),
                    downId = zlContext.generateId();
                h.push('<div  class="layui-row layui-col-space10">');
                h.push('    <div id ="' + upId + '" class="layui-col-md12"></div>');
                h.push('    <div id ="' + downId + '" class="layui-col-md12"></div>');
                h.push('</div>');
                $parent.append(h.join(''));
                return { up: $('#' + upId), down: $('#' + downId) };
            },
            /**渲染按钮 返回按钮的id数组*/
            buttons: function (options, $parent, buttonsOptions) {
                var h = [],
                    btnIds = [];
                if (buttonsOptions && buttonsOptions.length > 0) {
                    h.push('<div class="layui-form-item"> <div class="layui-input-block">');
                    $.each(buttonsOptions, function (i, button) {
                        var btnId = zlContext.generateId(),
                            sumbit = button.id == 'submit' ? ' lay-submit ' : '',
                            disabled = button.disabled && button.disabled == 1 ? '  disabled="" ' : '',
                            filter = ' lay-filter="' + btnId + '"',
                            id = ' id="' + btnId + '"';
                        btnIds.push(btnId);
                        h.push('<button class="layui-btn layui-btn-sm" class="layui-btn" url="' + button.url + '"' + id + sumbit + filter + disabled + '>' + button.text + '</button>');
                    });
                    h.push('</div></div>');
                    $parent.append(h.join(''));
                }
                return btnIds;
            },
            /**渲染 fieldset*/
            fieldset: function (options, $parent, fieldOptions) {
                var fhtml = [];
                fhtml.push('<fieldset class="layui-elem-field layui-field-title' + (fieldOptions.hide && fieldOptions.hide == 1 ? ' layui-hide ' : '') + '" style="margin-top: 20px;">');
                fhtml.push('<legend>' + fieldOptions.title + '</legend>');
                fhtml.push('</fieldset>');
                $parent.append(fhtml.join(''));
            },
            /**渲染 checkbox*/
            checkbox: function (options, $parent, fieldOptions) {
                var fhtml = [],
                    disabled = fieldOptions.disabled && fieldOptions.disabled == 1 ? '  disabled="" ' : '',
                    hide = fieldOptions.hide && fieldOptions.hide == 1 ? ' layui-hide ' : '',
                    filter = ' lay-filter="' + fieldOptions.field + '"';
                fhtml.push('<div class="layui-col-md' + fieldOptions.width + hide + '">');
                fhtml.push(' <label class="layui-form-label">' + fieldOptions.title + '</label>');
                if (options.res && fieldOptions.res && options.res[fieldOptions.res]) {
                    $.each(options.res[fieldOptions.res], function (resindex, r) {
                        fhtml.push('<input type="checkbox" ' + disabled + filter + ' name="' + fieldOptions.field + '[' + r.value + ']" title="' + r.name + '" ' + (r.value == fieldOptions.defaultValue ? 'checked' : '') + '>');
                    });
                } else
                    fhtml.push('     <input type="checkbox" ' + disabled + filter + ' name="' + fieldOptions.field + '[]" title="' + fieldOptions.title + '" ' + (fieldOptions.defaultValue ? 'checked' : '') + '>');
                fhtml.push('</div>');
                $parent.append(fhtml.join(''));
            },
            /**渲染 checkbox*/
            switchbox: function (options, $parent, fieldOptions) {
                var fhtml = [],
                    name = ' name="' + fieldOptions.field + '"',
                    defaultValue = (fieldOptions.defaultValue ? ' checked' : ''),
                    disabled = fieldOptions.disabled && fieldOptions.disabled == 1 ? '  disabled="" ' : '',
                    hide = fieldOptions.hide && fieldOptions.hide == 1 ? ' layui-hide ' : '',
                    filter = ' lay-filter="' + fieldOptions.field + '"';
                fhtml.push('<div class="layui-col-md' + fieldOptions.width + hide + '">');
                fhtml.push(' <label class="layui-form-label">' + fieldOptions.title + '</label>');
                fhtml.push('     <input type="checkbox" ' + disabled + filter + name + defaultValue + ' lay-skin="switch" lay-text="开启|关闭">');
                fhtml.push('</div>');
                $parent.append(fhtml.join(''));
            },
            /**渲染 combox*/
            combox: function (options, $parent, fieldOptions) {
                var fhtml = [],
                    verify = fieldOptions.verify ? ' lay-verify="' + fieldOptions.verify + '"' : '',
                    name = ' name="' + fieldOptions.field + '"',
                    disabled = fieldOptions.disabled && fieldOptions.disabled == 1 ? '  disabled="" ' : '',
                    placeholder = fieldOptions.placeholder ? fieldOptions.placeholder : '',
                    hide = fieldOptions.hide && fieldOptions.hide == 1 ? ' layui-hide ' : '',
                    search = (fieldOptions.search ? ' lay-search=""' : '');
                fhtml.push('<div class="layui-col-md' + fieldOptions.width + hide + '">');
                fhtml.push(' <label class="layui-form-label">' + fieldOptions.title + '</label>');
                fhtml.push(' <div class="layui-input-block">');
                fhtml.push('   <select ' + disabled + ' lay-filter="' + fieldOptions.field + '"' + name + verify + search + '>');
                fhtml.push('        <option value="">' + placeholder + '</option>');
                if (options.res && fieldOptions.res && options.res[fieldOptions.res])
                    $.each(options.res[fieldOptions.res], function (resindex, r) {
                        if (r.childs) {
                            fhtml.push('<optgroup label="' + r.name + '">');
                            $.each(r.childs, function (cindex, cr) {
                                fhtml.push('<option value="' + cr.value + '" ' + (cr.value == fieldOptions.defaultValue ? 'selected' : '') + '>' + cr.name + '</option>');
                            });
                            fhtml.push('</optgroup>');
                        }
                        else
                            fhtml.push('<option value="' + r.value + '" ' + (r.value == fieldOptions.defaultValue ? 'selected' : '') + '>' + r.name + '</option>');
                    });
                fhtml.push('   </select>');
                fhtml.push('</div></div>');
                $parent.append(fhtml.join(''));
            },
            /**渲染 radio*/
            radio: function (options, $parent, fieldOptions) {
                var fhtml = [],
                    disabled = fieldOptions.disabled && fieldOptions.disabled == 1 ? ' disabled="" ' : '',
                    hide = fieldOptions.hide && fieldOptions.hide == 1 ? ' layui-hide ' : '',
                    filter = ' lay-filter="' + fieldOptions.field + '"',
                    name = ' name="' + fieldOptions.field + '"';
                fhtml.push('<div class="layui-col-md' + fieldOptions.width + hide + '">');
                fhtml.push(' <label class="layui-form-label">' + fieldOptions.title + '</label>');
                fhtml.push(' <div class="layui-input-block">');
                if (options.res && fieldOptions.res && options.res[fieldOptions.res]) {
                    $.each(options.res[fieldOptions.res], function (resindex, r) {
                        var defaultValue = (r.value == fieldOptions.defaultValue ? ' checked' : '');
                        fhtml.push('<input type="radio" ' + filter + name + disabled + 'value="' + r.value + '" title="' + r.name + '" ' + defaultValue + '>');
                    });
                }
                fhtml.push(' </div>');
                fhtml.push('</div>');
                $parent.append(fhtml.join(''));
            },
            /**渲染 textarea*/
            textarea: function (options, $parent, fieldOptions) {
                var fhtml = [],
                    defaultValue = (fieldOptions.defaultValue ? fieldOptions.defaultValue : ''),
                    verify = fieldOptions.verify ? ' lay-verify="' + fieldOptions.verify + '"' : '',
                    placeholder = fieldOptions.placeholder ? ' placeholder="' + fieldOptions.placeholder + '"' : '',
                    name = ' name="' + fieldOptions.field + '"',
                    disabled = fieldOptions.disabled && fieldOptions.disabled == 1 ? '  disabled="" ' : '',
                    hide = fieldOptions.hide && fieldOptions.hide == 1 ? ' layui-hide ' : '',
                    filter = ' lay-filter="' + fieldOptions.field + '"';
                fhtml.push('<div class="layui-col-md' + fieldOptions.width + (fieldOptions.hide && fieldOptions.hide == 1 ? ' layui-hide ' : '') + '">')
                fhtml.push(' <label class="layui-form-label">' + fieldOptions.title + '</label>');
                fhtml.push(' <div class="layui-input-block">');
                fhtml.push('   <textarea  class="layui-textarea"' + filter + placeholder + name + disabled + verify + '>' + defaultValue + '</textarea>');
                fhtml.push(' </div>');
                fhtml.push('</div>');
                $parent.append(fhtml.join(''));
            },
            /**渲染 attachment*/
            attachment: function (options, $parent, fieldOptions) {
                var fhtml = [],
                    uplvId = 'upload_' + zlContext.generateId(),
                    upacId = 'uploadaction_' + zlContext.generateId(),
                    uptbId = 'uploadaction_' + zlContext.generateId();
                $parent.append([
                    '<div class="layui-col-md' + fieldOptions.width + (fieldOptions.hide && fieldOptions.hide == 1 ? ' layui-hide ' : '') + '">'
                    , '<label class="layui-form-label">' + fieldOptions.title + '</label>'
                    , '<div class="layui-input-block">'
                    , '<div class="layui-upload">'
                    , '<button type="button" class="layui-btn layui-btn-normal' + (fieldOptions.disabled && fieldOptions.disabled == 1 ? ' layui-btn-disabled' : '"') + ' id="' + uplvId + '">选择多文件</button>'
                    , '<div class="layui-upload-list">'
                    , '<table class="layui-table">'
                    , ' <thead>'
                    , '     <tr><th>文件名</th>'
                    , '     <th>大小</th>'
                    , '     <th>状态</th>'
                    , '     <th>操作</th>'
                    , '  </tr></thead>'
                    , '<tbody id="' + uptbId + '"></tbody>'
                    , '</table>'
                    , '</div>'
                    , '<button type="button" class="layui-btn" id="' + upacId + '">开始上传</button>'
                    , '</div></div></div>'
                ].join(''));
                //多文件列表示例
                var updloadListView = $('#' + uptbId)
                    , uploadListIns = upload.render({
                        elem: '#' + uplvId
                        , url: fieldOptions.url
                        , accept: 'file'
                        , multiple: fieldOptions.filecount > 0
                        , auto: false
                        , bindAction: '#' + upacId
                        , choose: function (obj) {
                            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                            //读取本地文件
                            obj.preview(function (index, file, result) {
                                var tr = $(['<tr id="upload-' + index + '">'
                                    , '<td>' + file.name + '</td>'
                                    , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                                    , '<td>等待上传</td>'
                                    , '<td>'
                                    , '<button class="layui-btn layui-btn-mini file-reload layui-hide">重传</button>'
                                    , '<button class="layui-btn layui-btn-mini layui-btn-danger file-delete">删除</button>'
                                    , '</td>'
                                    , '</tr>'].join(''));
                                //单个重传
                                tr.find('.file-reload').on('click', function () {
                                    obj.upload(index, file);
                                });
                                //删除
                                tr.find('.file-delete').on('click', function () {
                                    delete files[index]; //删除对应的文件
                                    tr.remove();
                                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                                });
                                updloadListView.append(tr);
                            });
                        }
                        , done: function (res, index, upload) {
                            if (res.code == 0) { //上传成功
                                var tr = updloadListView.find('tr#upload-' + index)
                                    , tds = tr.children();
                                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                                tds.eq(3).html(''); //清空操作
                                return delete this.files[index]; //删除文件队列已经上传成功的文件
                            }
                            this.error(index, upload);
                        }
                        , error: function (index, upload) {
                            var tr = updloadListView.find('tr#upload-' + index)
                                , tds = tr.children();
                            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
                            tds.eq(3).find('.file-reload').removeClass('layui-hide'); //显示重传
                        }
                    });
            },
            innerDateTime: function (options, $parent, fieldOptions) {
                var fhtml = [],
                    dtId = 'datetime_' + zlContext.generateId(),
                    verify = fieldOptions.verify ? ' lay-verify="' + fieldOptions.verify + '"' : '',
                    placeholder = fieldOptions.placeholder ? ' placeholder="' + fieldOptions.placeholder + '"' : '',
                    name = ' name="' + fieldOptions.field + '"',
                    disabled = fieldOptions.disabled && fieldOptions.disabled == 1 ? '  disabled="" ' : '',
                    id = ' id="' + dtId + '"',
                    filter = ' lay-filter="' + fieldOptions.field + '"';
                fhtml.push('<div class="layui-col-md' + fieldOptions.width + (fieldOptions.hide && fieldOptions.hide == 1 ? ' layui-hide ' : '') + '">');
                fhtml.push(' <label class="layui-form-label">' + fieldOptions.title + '</label>');
                fhtml.push(' <div class="layui-input-block">');
                fhtml.push('   <input type="text" class="layui-input" ' + filter + disabled + id + name + verify + placeholder + '>');
                fhtml.push(' </div>');
                fhtml.push('</div>');
                $parent.append(fhtml.join(''));
                var dtSetting = {
                    elem: dtId
                    , format: fieldOptions.format
                }
                fieldOptions.defaultValue ? dtSetting.value = fieldOptions.defaultValue : '';
                laydate.render(dtSetting);
                return dtId;
            },
            /**日期渲染 */
            date: function (options, $parent, fieldOptions) {
                return componentRender.datetime(options, $parent, fieldOptions);
            },
            /**时间渲染 */
            time: function (options, $parent, fieldOptions) {
                return componentRender.datetime(options, $parent, fieldOptions);
            },
            /**年渲染 */
            year: function (options, $parent, fieldOptions) {
                return componentRender.datetime(options, $parent, fieldOptions);
            },
            /**月渲染 */
            month: function (options, $parent, fieldOptions) {
                return componentRender.datetime(options, $parent, fieldOptions);
            },
            /**时间渲染 */
            datetime: function (options, $parent, fieldOptions) {
                var dtId = componentRender.innerDateTime(options, $parent, fieldOptions);
                laydate.render({
                    elem: '#' + dtId
                    , type: fieldOptions.type
                    , format: fieldOptions.format
                })
                return dtId;
            },
            /**事件范围渲染 */
            datetimerange: function (options, $parent, fieldOptions) {
                componentRender
                var dtId = componentRender.innerDateTime(options, $parent, fieldOptions);
                laydate.render({
                    elem: '#' + dtId

                    , format: fieldOptions.format
                    , range: true
                })
                return dtId;
            },
            /**自定义时间渲染 */
            customdate: function (options, $parent, fieldOptions) {
                var dtId = componentRender.innerDateTime(options, $parent, fieldOptions);
                var dtconfig = {
                    elem: '#' + dtId
                };
                $.extend(dtconfig, fieldOptions);
                laydate.render(dtconfig);
                return dtId;
            },
            /**输入框渲染 */
            textbox: function (options, $parent, fieldOptions) {
                var fhtml = [],
                    verify = fieldOptions.verify ? ' lay-verify="' + fieldOptions.verify + '"' : '',
                    placeholder = fieldOptions.placeholder ? ' placeholder="' + fieldOptions.placeholder + '"' : '',
                    name = ' name="' + fieldOptions.field + '"',
                    disabled = fieldOptions.disabled && fieldOptions.disabled == 1 ? '  disabled="" ' : '',
                    defaultValue = fieldOptions.defaultValue ? ' value="' + fieldOptions.defaultValue + '"' : '',
                    hide = fieldOptions.hide && fieldOptions.hide == 1 ? ' layui-hide ' : '',
                    filter = ' lay-filter="' + fieldOptions.field + '"';
                fhtml.push('<div class="layui-col-md' + fieldOptions.width + hide + '">');
                fhtml.push(' <label class="layui-form-label">' + fieldOptions.title + '</label>');
                fhtml.push(' <div class="layui-input-block">');
                fhtml.push('   <input type="text" class="layui-input" ' + filter + disabled + name + verify + placeholder + defaultValue + '>');
                fhtml.push(' </div>');
                fhtml.push('</div>');
                $parent.append(fhtml.join(''));
            },
            /**脚本渲染 */
            scripts: function (scriptsOptions) {
                if (scriptsOptions && scriptsOptions.length > 0) {
                    $(scriptsOptions).each(function (i, script) {
                        var script = $('<script>' + script + '<\/script>');
                        console.log(script);
                        $('body').append(script);
                    })
                }
            },
            /**form严重渲染 */
            verifys: function (verifysOptions) {
                if (verifysOptions && verifysOptions.length > 0) {
                    $(verifysOptions).each(function (i, src) {
                        for (var p in src) {
                            var s = $('<script>' + src[p] + '<\/script>');
                            $('body').append(s);
                        }
                    })
                }
            }
        }
    exports("zlComponentRender", zlComponentRender)
});